package com.hmall.gateway.filter;

import com.hmall.gateway.utils.JwtTool;
import com.hmall.gateway.config.AuthProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    private final JwtTool JwtTool;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    private final AuthProperties authProperties;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1、获取Request
        ServerHttpRequest request = exchange.getRequest();
        System.out.println(request.getPath().value());
        // 2、判断是否需要拦截
        if(isExclude(request.getPath().value())){
            // 2.1.不需要拦截，放行
            return chain.filter(exchange);
        }
        // 3、获取请求头中的token
        String token = request.getHeaders().getFirst("authorization");

        // 4、校验并解析token
        Long userId = null;
        try{
            userId = JwtTool.parseToken(token);
        }catch (Exception e){
            // 4.1.无效，返回401
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.valueOf(401));
            return response.setComplete();
        }


        // 5、如果有效，传递用户信息
        System.out.println("userId = " + userId);
        String userInfo = userId.toString();
        ServerWebExchange ex = exchange.mutate().request(b -> b.header("user-info", userInfo)).build();

        // 6、放行
        return chain.filter(ex);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private boolean isExclude(String antPath) {
        for (String pathPattern : authProperties.getExcludePaths()) {
            if(antPathMatcher.match(pathPattern, antPath)){
                return true;
            }
        }
        return false;
    }
}
